/**
 * Created by xu on 2015/11/27.
 */
//$.ajaxSettings.traditional = true;参数提交方式
/**
 * 如果是要不做任何处理，直接要最原始的内容，java请用
 * AjaxResponse.sendText
 * js请加参数{"stringFormat":true}
 */
//一些正则
var phoneRegx_=/^1\d{10}$/;//手机号码
var zuojiRegx_=/^0\d{2,3}-?\d{7,8}$/;//座机
var emailRegx_=/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;//邮箱
var jsonFormatRegx_ = /^\s*\{[\s\S]*\}\s*$/m;//json
var dateRegx = /^\d{4}-(0?[1-9]|1[0-2])-(0?[1-9]|[1-2]\d|3[0-1])$/;//日期格式
var timeRegx = /^([0-1]\d|2[0-3]):[0-5]\d:[0-5]\\d$/;  //时间

// /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/ ;
// /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
var date_time_Regx = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/; ;//日期时间

(function($){
    $.fn.invoke = function (url, param, fun, config) {
        try {
            if (url == null || url.endWith("null")) {
                return;
            }
        } catch (e) {
            console.log(url+">>>"+e)
        }
        param = param || {};
        if(!Base.isArray(fun)) {
            fun = [fun];
        }
        config = $.extend({}, $.fn.invoke.defaultConfig, config);
        //alert(typeof event)
        if ((typeof event)=='undefined'){
            config.isConverEventElement=false;
        }
        if (config.isConverEventElement){
            var eventTarget_=event.target || event.srcElement
            //console.log(eventTarget_.body)
            if (eventTarget_!=null && eventTarget_!=document){
                try {
                    if ($(eventTarget_).hasClass("blockUI")){
                        event.stopPropagation();
                        return;
                    }
                   // console.log(eventTarget_.outerHTML)
                    $(eventTarget_).block({ message: null});
                }
                catch (e){
                    console.log(e)
                }
            }
        }

        //追加参数
        if(Base.isArray(param)) {
            param.push({name: "_random", value: Math.random()}, {name: "AjaxMode", value: "ajaxFlag"});
            if(_token!=null && _token!=''){
                param.push({name:"_token",value:_token});
            }
        } else if(typeof param == "object") {
            param["_random"] = Math.random();
            param["AjaxMode"] = "ajaxFlag";
            if(_token!=null && _token!=''){
                param["_token"] = _token;
            }
        } else if(Base.isString(param)) {
            if(param.length && param.charAt(param.length - 1) != '&')
                param += "&";
            param += "_random=" + Math.random() + "&AjaxMode=ajaxFlag";
            if(_token!=null && _token!=''){
                param+="&_token="+_token;
            }
        }

        if(url.indexOf("?")==-1){
            url+="?math1="+Math.random();
        }else{
            url+="&math1="+Math.random();
        }
        var self = this;
        var jsonFormat = /^\s*\{[\s\S]*\}\s*$/m;
        $.ajax({
            url: url,
            type: config.type,
            dataType: config.dataType,
            async: config.async,
            data: param,
            complete: function (res, status) {
                if (config.isConverEventElement){
                    $(eventTarget_).unblock();
                   // if (config.source=="button"){
                        $('.blockUI').remove();
                   // }
                }
                var responseText = res.responseText;
                if(status == "success" || status == "notmodified") {
                    if (config.stringFormat){

                        fun[0].apply(self, ["success",responseText] );
                        return;
                    }else {
                        if(jsonFormat.test(responseText)) {
                            var _res = eval("(" + responseText + ")");
                            if ((_res["needFormat_"] =='need')){

                                if(_res["bool"] === false) {
                                    if (_res["message"] == 'sessionStatusFalse') {//如果是session过期错误
                                        alert("登陆已超时或者帐号已在别处登陆!");
                                        top.location = p_path + '/index.html';
                                        return;
                                    }else if (_res["message"] == 'paramFail'){//非法参数
                                        alert(_res["result"]);
                                        return;
                                    }else {
                                        alert(_res["result"]);
                                        return;
                                    }
                                }else {
                                    fun[0].apply(self, [_res["message"], _res["result"]]);
                                }

                            }else {
                                fun[0].apply(self, ["success",responseText]);
                            }

                        }else {
                            //fun[0].apply(self, responseText);
                            flashMessage_(responseText)
                            //alert('数据格式不对');
                            console.log(responseText);
                        }
                    }
                    return;
                }else if(status == "error"){
                    console.log(responseText);
                    if(jsonFormat.test(responseText)
                        && responseText.indexOf('needFormat_')>-1) {
                        var _res = eval("(" + responseText + ")");
                        fun[1] ? fun[1].apply(self, [_res["message"], _res["result"]]) : (alert(_res["result"]));

                        return
                    }else {
                        if(responseText==null || responseText==''){return;}
                        Base.handleException(res);
                        //fun[1].apply(self, [responseText]);
                    }
                    return;
                }
            }
        });
        return this;
    };
    $.fn.invoke.defaultConfig = {type: "POST", dataType: "html", async: true,
        ajaxMode: "ajaxFlag","isConverEventElement":true,"stringFormat":false,"source":"button"};


    $.fn.serializeFormJSON = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

})(jQuery);
var Base={
    isArray: function (object) {
        return object && object.constructor === Array;
    },
    isFunction: function (object) {
        return typeof object == "function";
    },
    isString: function (object) {
        return typeof object == "string";
    },
    isNumber: function (object) {
        return typeof object == "number";
    },
    isUndefined: function (object) {
        return typeof object == "undefined";
    },
    token: function (async) {
        var refUrl=location.href;
        if(refUrl.indexOf("mainFrame.do")>-1){return;}
        async = async === undefined ? true : async;
        $().invoke(p_path+"/ajax/getToken.do", {}, function (message, re) {
            _token=re;
        }, {"async": async});
    },
    handleException: function (exception) {
        var erM='请求出错了！';
        if(exception!=null && exception.responseText!=null && exception.responseText !=''){
            erM=exception.responseText;
        }
        if (erM!=null && erM.indexOf("org.apache.shiro.session.UnknownSessionException")>-1){
            alert("登陆已超时或者帐号已在别处登陆!");
            top.location = p_path + '/index.html';
            return;
        }
        flashMessage_(erM);
    }
};



/**一闪即逝的提示*/
function flashMessage_(erM){

    //var obj=window.self;
    if(self.location!=top.location){
        top.flashMessage_(erM);
        return;
    }

    $.blockUI({
        message: erM,
        fadeIn: 700,
        fadeOut: 700,
        timeout: 5000,
        showOverlay: false,
        centerY: false,
        css: {
            width: '350px',
            top: '50%',
            //bottom:'10%',
            left: '',
            right: '10px',
            border: 'none',
            padding: '5px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: .6,
            color: '#fff'
        }
    });
};


/**
 * 串行加载
 * @param scripts
 * @param callback
 */
function seriesLoadScripts(scripts,callback) {
    if(typeof(scripts) != "object") var scripts = [scripts];
    var HEAD = document.getElementsByTagName("head").item(0) || document.documentElement;
    var s = new Array(), last = scripts.length - 1, recursiveLoad = function(i) {  //递归
        s[i] = document.createElement("script");
        s[i].setAttribute("type","text/javascript");
        s[i].onload = s[i].onreadystatechange = function() { //Attach handlers for all browsers
            if(!/*@cc_on!@*/0 || this.readyState == "loaded" || this.readyState == "complete") {
                this.onload = this.onreadystatechange = null; this.parentNode.removeChild(this);
                if(i != last) recursiveLoad(i + 1); else if(typeof(callback) == "function") callback();
            }
        }
        s[i].setAttribute("src",scripts[i]);
        HEAD.appendChild(s[i]);
    };
    recursiveLoad(0);
}

/**
 * 并行加载
 * @param scripts
 * @param callback
 */
function parallelLoadScripts(scripts,callback) {
    if(typeof(scripts) != "object") var scripts = [scripts];
    var HEAD = document.getElementsByTagName("head").item(0) || document.documentElement, s = new Array(), loaded = 0;
    for(var i=0; i<scripts.length; i++) {
        s[i] = document.createElement("script");
        s[i].setAttribute("type","text/javascript");
        s[i].onload = s[i].onreadystatechange = function() { //Attach handlers for all browsers
            if(!/*@cc_on!@*/0 || this.readyState == "loaded" || this.readyState == "complete") {
                loaded++;
                this.onload = this.onreadystatechange = null; this.parentNode.removeChild(this);
                if(loaded == scripts.length && typeof(callback) == "function") callback();
            }
        };
        s[i].setAttribute("src",scripts[i]);
        HEAD.appendChild(s[i]);
    }
}

function json2UrlParam(json){
    var pp="";
    for (var key in json){
        pp+=key+"="+json[key]+"&";
    }
    return pp;
}


//页面的url地址和左侧菜单的对应关系
var url_menu_Map=new Map();

url_menu_Map.put(p_path+"/pipe/PipeCrossDataM/pipeDataManager.html",p_path+"/pipe/PipeCrossDataM/pipeDataManager.html");

url_menu_Map.put(p_path+"/cleanTask/cleanPipeLineManager/goPiggingManagerPage.html",p_path+"/cleanTask/cleanPipeLineManager/goPiggingManagerPage.html");
url_menu_Map.put(p_path+"/cleanTask/cleanPipeLineManager/addOrModify.html",p_path+"/cleanTask/cleanPipeLineManager/goPiggingManagerPage.html");

url_menu_Map.put(p_path+"/cleanTask/cleanPipeLineHistory/getCleanPipeLineHistoryIndex.html",p_path+"/cleanTask/cleanPipeLineHistory/getCleanPipeLineHistoryIndex.html");
url_menu_Map.put(p_path+"/cleanTask/cleanPipeLineHistory/goEvluation.html",p_path+"/cleanTask/cleanPipeLineHistory/getCleanPipeLineHistoryIndex.html");


url_menu_Map.put(p_path+"/cleanTask/cleanPipeLineTrack/getCleanPipeLineTrackIndex.html",p_path+"/cleanTask/cleanPipeLineTrack/getCleanPipeLineTrackIndex.html");
url_menu_Map.put(p_path+"/cleanTask/cleanPipeLineTrack/getTrackDetail.html.html",p_path+"/cleanTask/cleanPipeLineTrack/getCleanPipeLineTrackIndex.html");


url_menu_Map.put(p_path+"/eqpt/equipment/equipmentInfo/equipmentInfoPage.html",p_path+"/eqpt/equipment/equipmentInfo/equipmentInfoPage.html");
url_menu_Map.put(p_path+"/eqpt/equipment/empUse/empUsePage.html",p_path+"/eqpt/equipment/equipmentInfo/equipmentInfoPage.html");
url_menu_Map.put(p_path+"/eqpt/equipment/extemalUse/extemalUsePage.html",p_path+"/eqpt/equipment/equipmentInfo/equipmentInfoPage.html");

url_menu_Map.put(p_path+"/settings/org/company/page.html",p_path+"/settings/org/company/page.html");
url_menu_Map.put(p_path+"/settings/user/authorizeManager.html",p_path+"/settings/org/company/page.html");
url_menu_Map.put(p_path+"/settings/pipe/toPipeValveroomMgr.html",p_path+"/settings/org/company/page.html");

//url地址下面有哪些tab
var _tabName_url=new Map();
_tabName_url.put(p_path+"/pipe/PipeCrossDataM/pipeDataManager.html",{
    "tabLevel1":[""],
    "tabContenID":"tab_li"
});
_tabName_url.put(p_path+"/settings/org/company/page.html",{
    "tabLevel1":[""],
    "tabContenID":"org"
});
_tabName_url.put(p_path+"/settings/user/authorizeManager.html",{
    "tabLevel1":[""],
    "tabContenID":"auth"
});
_tabName_url.put(p_path+"/settings/pipe/toPipeValveroomMgr.html",{
    "tabLevel1":[""],
    "tabContenID":"baseSetting"
});


function reDirectUrl(){
    if (_nowUrlPath.endWith("cleanPipeLineTrack/getTrackDetail.html")||
        _nowUrlPath.endWith("cleanPipeLineHistory/goEvluation.html")||
        _nowUrlPath.endWith("cleanPipeLineManager/addOrModify.html")){
        var _url=window.location;
        $("#house-frame").attr("src",_url);
        //var menuLi=url_menu_Map.get(window.location.pathname);
        var uuu=window.location.pathname;
        activeLMenu(uuu)
    }else
    if (_nowUrlPath.endWith("pipeIndex.html")){
        var _url_ =localStorage.getItem(_nowPage_url_CacheName);

        if (isEmpty(_url_)){
            _url_=p_path+"/cleanTask/cleanPipeLineTrack/getCleanPipeLineTrackIndex.html";
        }
        if (_url_.endWith("pipeIndex.html")){
            return;
        }

        $("#house-frame").attr("src",_url_);
        activeLMenu(_url_)
        //$("#house-frame").prop("src");
    }

    else {
        var _tab_ =localStorage.getItem(_nowPage_tab_CacheName);
        var conIdObj=_tabName_url.get(_nowUrlPath);
        if (!isEmpty(conIdObj)){
            var conId=conIdObj.tabContenID;
            if (isEmpty(conId)){
                return;
            }
            $("li[tabName="+_tab_+"]",$("#"+conId)).trigger("click");
        }

    }
    if (_nowUrlPath.endWith("pipeIndex.html")||_nowUrlPath.endWith("upLoadPage.html")){
        return;
    }
    if (_nowUrlPath.endWith("cleanPipeLineTrack/getTrackDetail.html")||
    _nowUrlPath.endWith("cleanPipeLineHistory/goEvluation.html")||
        _nowUrlPath.endWith("cleanPipeLineManager/addOrModify.html")){
        localStorage.setItem(_nowPage_url_CacheName,window.location);
        return;
    }
    localStorage.setItem(_nowPage_url_CacheName,_nowUrlPath);
}


function getlen(str1,str2){
    var r=new RegExp(str2,"gi");
    return str1.match(r).length;
}



function activeLMenu(_url_){
    _url_=getNoParamUrl(_url_);
    if (_url_.startWith("http")){
        var ua1=_url_.match(/([^\/]*\/){2}([^\/]*)/)[2];
        _url_=_url_.replace("http://"+ua1,"");
    }

    var menuLi=url_menu_Map.get(_url_);
    if (menuLi==null){
        return;
    }
    $("#leftBar ul li").each(function(i,d){
        if ($("a",$(d)).attr("href")==menuLi){
            $("#leftBar ul *").removeClass("active");
            $(d).addClass("active");
            $("a",$(d)).addClass("active");
        }
    });
}

function cleanMenuUrl(){
    localStorage.setItem(_nowPage_url_CacheName,"");
    localStorage.setItem(_nowPage_tab_CacheName,"");
    top.location=p_path+"/pipe/pipeIndex.html";
}

function activeTopLMenu(url){
    window.top.activeLMenu(url)
}